﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace KingSite.Library.IO {
    public static class StreamUtility {
        // Methods
        public static void SaveToFile(this Stream stream, string filename) {
            using (FileStream stream2 = new FileStream(filename, FileMode.Create)) {
                int count = 0;
                byte[] buffer = new byte[0x400];
                while ((count = stream.Read(buffer, 0, buffer.Length)) > 0) {
                    stream2.Write(buffer, 0, count);
                }
                stream2.Flush();
            }
        }

        public static int Search(this Stream stream, byte[] data, int startIndex) {
            return stream.Search(data, startIndex, ((int)stream.Length));
        }

        public static int Search(this Stream stream, byte[] data, int startIndex, int count) {
            if ((data != null) && (data.Length != 0)) {
                if (stream.Length == 0L) {
                    return -1;
                }
                if ((stream.Length < data.Length) || (count <= 0)) {
                    return -1;
                }
                if (stream.CanSeek) {
                    long num = Math.Min(stream.Length - 1L, (long)((startIndex + count) - 1));
                    for (int i = startIndex; i <= num; i++) {
                        int num3 = 0;
                        for (int j = 0; j < data.Length; j++) {
                            stream.Position = i + j;
                            if (((i + j) > num) || (stream.ReadByte() != data[j])) {
                                break;
                            }
                            num3++;
                        }
                        if (num3 == data.Length) {
                            return i;
                        }
                    }
                }
            }
            return -1;
        }

        public static byte[] ToBytes(this Stream stream) {
            return stream.ToMemoryStream().ToArray();
        }

        public static MemoryStream ToMemoryStream(this Stream stream) {
            MemoryStream stream2 = stream as MemoryStream;
            if (stream2 == null) {
                stream2 = new MemoryStream();
                byte[] buffer = new byte[0x400];
                int count = 0;
                while ((count = stream.Read(buffer, 0, buffer.Length)) > 0) {
                    stream2.Write(buffer, 0, count);
                }
            }
            stream2.Seek(0L, SeekOrigin.Begin);
            return stream2;
        }

        public static string ToString(this Stream stream, Encoding encoding) {
            return encoding.GetString(stream.ToBytes());
        }

    }



}
